package mysql

import (
	"gorm.io/gorm"
	"me/123/common/global"
	"me/123/common/model"

	"time"
)

func ProductList(query *gorm.DB, offset int64, size int64) (result []*model.EbStoreProduct, err error) {
	err = query.Offset(int(offset)).Limit(int(size)).Find(&result).Error
	if err != nil {
		return nil, err
	}
	return result, nil
}

func ProductCateList(ds []int64, query *gorm.DB) (result []*model.EbStoreProduct, err error) {
	err = global.DB.Model(&model.EbStoreProduct{}).Where("cate_id IN ?", ds).Find(&result).Error
	return
}

func Scan(category int64) (categoryLevel int64, err error) {
	err = global.DB.Model(&model.EbStoreCategory{}).Select("pid").Where("id=?", category).Scan(&categoryLevel).Error
	return
}

func Pluck(category int64) ([]int64, error) {
	var subCategoryIDs []int64
	subCategoryIDs = append(subCategoryIDs, category)
	err := global.DB.Model(&model.EbStoreCategory{}).Where("pid=?", category).Pluck("id", &subCategoryIDs).Error
	if err != nil {
		return nil, err
	}
	return subCategoryIDs, nil
}

func KeywordQuery(keyword string, query *gorm.DB) (result []*model.EbStoreProduct, err error) {
	err = query.Where("keyword like ?", "%"+keyword+"%").Find(&result).Error
	return
}

func IsNewQuery(oneMonthAgo time.Time, query *gorm.DB) (result []*model.EbStoreProduct, err error) {
	err = query.Where("created_at>?", oneMonthAgo).Find(&result).Error
	return
}

func QueryList(query *gorm.DB) (result []*model.EbStoreProduct, err error) {
	err = query.Find(&result).Error
	return
}

func QueryProductInfo(id int64) (result *model.EbStoreProduct, err error) {
	err = global.DB.Where("id = ?", id).Limit(1).Find(&result).Error
	return
}

func UpdateProductStock(id int32, stock int32, tx *gorm.DB) error {
	return tx.Model(&model.EbStoreProduct{}).Where("id = ?", id).Update("stock", stock).Error

}

func QueryUserRecommended(userId int64) (result []*model.EbStoreProduct, err error) {
	err = global.DB.Model(&model.EbStoreProduct{}).
		Joins("LEFT JOIN orders ON eb_store_product.id = orders.products_id AND orders.user_id =?", userId).
		Select("eb_store_product.*, COUNT(orders.id) AS order_count").
		Group("eb_store_product.id").
		Order("order_count DESC").
		Find(&result).Error
	return
}
